import type { FC } from 'react';
import { useRouter } from 'expo-router';
import { useMemoizedFn, useSafeState } from 'ahooks';
import { View, ScrollView, Text } from 'react-native';

import {
  Space,
  Button,
  Password,
  PageWrapper,
  CoverImage,
  HollowText,
  EmailInput,
  globalLoading
} from '@/components';

import useUserModel from '@/models/user';
import { useLoadingState } from '@/hooks/useLoadingState';
import GoogleIcon from '@/assets/icons/google_icon.svg';
import FacebookIcon from '@/assets/icons/facebook_icon.svg';

import styles from './styles';

const Signin: FC = () => {
  const router = useRouter();
  const user = useUserModel();
  const [loading] = useLoadingState();
  const [email, setEmail] = useSafeState<string>('zhaoming@yuan.com');
  const [password, setPassword] = useSafeState<string>('PWD123456');

  const onLogin = useMemoizedFn(async () => {
    globalLoading.open(false);
    await user.login({
      email,
      password
    });
    globalLoading.close();
  });

  const toSignup = useMemoizedFn(() => {
    router.push('/signup');
  });

  return (
    <PageWrapper>
      <View style={styles.wrapper}>
        <CoverImage style={styles.cover}>
          <HollowText fontSize={36}>
            LOGIN
          </HollowText>
        </CoverImage>
        <View style={styles.container}>
          <ScrollView style={styles.content}>
            <Space direction="vertical" size={20}>
              <EmailInput
                value={email}
                onChange={setEmail}
                placeholder="Email address"
              />
              <Password
                value={password}
                onChange={setPassword}
                placeholder="Password"
              />
            </Space>
            <View style={styles.forgot_pwd}>
              <Button
                type="link"
                size="small"
                title="Forgot password?"
              />
            </View>
            <View style={styles.submitter}>
              <Button
                round
                type="primary"
                title="Log in"
                onPress={onLogin}
                loading={loading}
              />
            </View>
            <View style={styles.other_login}>
              <Space size={24}>
                <GoogleIcon />
                <FacebookIcon />
              </Space>
            </View>
            <Text style={styles.footer_text}>
              {`Don't have account? `}
              <Text
                style={styles.signup}
                onPress={toSignup}
              >
                Sign up
              </Text>
            </Text>
          </ScrollView>
        </View>
      </View>
    </PageWrapper>
  );
}

export default Signin;